<template>
  <div>
    <div class="header">群模式</div>
    <div style="margin:10px;">
      <kv label="我的用户名"><el-input v-model="userId"></el-input> </kv>

      <kv label="房间号">{{room._id}}</kv>
      <kv label="用户">{{room.users.join(",")}}</kv>
    </div>
    <div>
      <div :class="{'user':1, 'selected' : talk_user=='abc' }" data-id="abc" @click="chat($event)">
        user1
      </div>
      <div :class="{'user':1, 'selected' : talk_user=='d' }" data-id="d" @click="chat($event)">
        user2
      </div>
      <div :class="{'user':1, 'selected' : talk_user=='e' }" data-id="e" @click="chat($event)">
        user3
      </div>
    </div>
    <div style="margin:10px;">
      <kv label="消息">
        <textarea v-model="msg"></textarea>
      </kv>
      <button @click="send">发送</button>
    </div>
    <ul style="margin:10px">
      <li v-for="(item,index) in list" :key="index">
        <span>{{item.user}}:</span>{{item.content}}
      </li>
    </ul>
  </div>
</template>
<style scoped>
  >>> .user {
    width: 100px;
    height: 100px;
    border: solid 1px green;
    background: #1ebcc5;
    display: inline-block;
    margin: 5px;
  }

  >>> .user.selected {
    border: solid 1px #2f3080;
    background: #c5c434;
  }

</style>
<script>
  import io from "socket.io-client"

  export default {
    data() {
      return {socket: null, room: {users: []}, talk_user: "abc", list: [], msg: "", userId: "1"}
    },
    mounted() {
    },
    methods: {
      init() {
        if (this.socket) {
          this.socket.close();
        }
        this.socket = io.connect("ws://localhost:3000");

        //接受消息
        this.socket.on('message', data => {
          this.list.push(data);
        });

        this.socket.on("chat", data => {
          this.room = data;
        });
      },
      chat(ev) {
        this.init();

        var id = ev.target.dataset.id
        this.talk_user = id


        this.socket.emit('chat', {master: this.userId, user: id});
      },
      send() {
        this.socket.emit("message", {user: this.userId, room_id: this.room._id, content: this.msg})
        this.msg = "";
      }
    }
  }
</script>
